/*
 * @Description: 城市选择UrbanChoice
 * @version: 
 * @Company: 
 * @Author: ZhengZhuang
 * @Date: 2019-08-21 17:13:10
 * @LastEditors: zhengzhuang
 * @LastEditTime: 2020-08-05 09:18:04
 */
import 'dart:convert';
import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:C20Driver/provider/position_information.dart';
import 'package:C20Driver/routers/navigator_util.dart';
import 'package:provider/provider.dart';
import 'package:C20Driver/model/city_model.dart';

class UrbanChoice extends StatefulWidget {
  @override
  _UrbanChoiceState createState() => _UrbanChoiceState();
}

class _UrbanChoiceState extends State<UrbanChoice> {
  List<CityInfo> _cityList = List();
  List<CityInfo> _hotCityList = List();

  int _suspensionHeight = 40;
  int _itemHeight = 50;
  String _suspensionTag = "";

  @override
  void initState() {
    super.initState();
    loadData();
  }

  void loadData() async {
    _hotCityList.add(CityInfo(name: "北京市", tagIndex: "★"));
    _hotCityList.add(CityInfo(name: "广州市", tagIndex: "★"));
    _hotCityList.add(CityInfo(name: "成都市", tagIndex: "★"));
    _hotCityList.add(CityInfo(name: "深圳市", tagIndex: "★"));
    _hotCityList.add(CityInfo(name: "杭州市", tagIndex: "★"));
    _hotCityList.add(CityInfo(name: "武汉市", tagIndex: "★"));

    //加载城市列表
    rootBundle.loadString('assets/data/china.json').then((value) {
      Map countyMap = json.decode(value);
      List list = countyMap['china'];
      list.forEach((value) {
        _cityList.add(CityInfo(name: value['name']));
      });
      _handleList(_cityList);
      setState(() {
        _suspensionTag = _hotCityList[0].getSuspensionTag();
      });
    });
  }

  void _handleList(List<CityInfo> list) {
    if (list == null || list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;
      if (RegExp("[A-Z]").hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = "#";
      }
    }
    //根据A-Z排序
    SuspensionUtil.sortListBySuspensionTag(_cityList);
  }

  void _onSusTagChanged(String tag) {
    setState(() {
      _suspensionTag = tag;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        title: Text("城市选择"),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Container(
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.only(left: 15.0),
              height: ScreenUtil().setWidth(100.0),
              child:
                  Consumer<PositionInformation>(builder: (ctx, state, child) {
                return Text("当前城市: ${state.driverCurrentCity}");
              }),
            ),
            Expanded(
              flex: 1,
              child: AzListView(
                data: _cityList,
                topData: _hotCityList,
                itemBuilder: (context, model) => _buildListItem(model),
                suspensionWidget: _buildSusWidget(_suspensionTag),
                isUseRealIndex: true,
                itemHeight: _itemHeight,
                suspensionHeight: _suspensionHeight,
                onSusTagChanged: _onSusTagChanged,
                //showCenterTip: false,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSusWidget(String susTag) {
    susTag = (susTag == "★" ? "热门城市" : susTag);
    return Container(
      height: _suspensionHeight.toDouble(),
      padding: const EdgeInsets.only(left: 15.0),
      color: Color(0xfff3f4f5),
      alignment: Alignment.centerLeft,
      child: Text(
        '$susTag',
        softWrap: false,
        style: TextStyle(
          fontSize: 14.0,
          color: Color(0xff999999),
        ),
      ),
    );
  }

  Widget _buildListItem(CityInfo model) {
    String susTag = model.getSuspensionTag();
    susTag = (susTag == "★" ? "热门城市" : susTag);
    return Column(
      children: <Widget>[
        Offstage(
          offstage: model.isShowSuspension != true,
          child: _buildSusWidget(susTag),
        ),
        SizedBox(
          height: _itemHeight.toDouble(),
          child: ListTile(
            title: Text(model.name),
            onTap: () async {
              // 返回选择城市model.name
              /// 地理编码（地址转坐标）
              // final geocodeList = await AmapSearch.searchGeocode(
              //   model.name,
              //   city: model.name,
              // );
              // await geocodeList[0].latLng.then((value) async {
              //   await AmapSearch.searchReGeocode(
              //     LatLng(value.latitude, value.longitude),
              //     radius: 200.0,
              //   ).then((ReGeocode res) async {
              //     // eventBus.fire(new SetMapLocation(LatLng(value.latitude, value.longitude)));
              //     Provider.of<PositionInformation>(context, listen: false).setCityLocation(model.name, value.latitude, value.longitude, await res.formatAddress, context);
              //     Navigator.of(context).pop();
              //   });
              // });
              NavigatorUtil.goBackWithParams(context, model.name);
            },
          ),
        )
      ],
    );
  }
}
